
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time
import csv
import pymongo
from fake_useragent import UserAgent
ua = UserAgent()
headers = {'User-Agent':ua.random}

client  = pymongo.MongoClient('localhost',27017)
mydb = client['pymongo']
qq_shuo = mydb['qq_shuo']
def get_info(qq):
    options = webdriver.ChromeOptions()
    options.add_argument('lang=zh_CN.UTF-8')
    options.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"')
    browser = webdriver.Chrome(options=options)
    url = "http://user.qzone.qq.com/{}/311".format(qq)
    print(url)
    browser.get(url)
    # browser.get("http://user.qzone.qq.com/980639151/311")
    action=ActionChains(browser)
    browser.implicitly_wait(5)
    try:
        browser.find_element_by_id('login_div')
        a = True
    except:
        a = False
    if a == True:
        browser.switch_to.frame('login_frame')
        browser.find_element_by_id('switcher_plogin').click()
        browser.find_element_by_id('u').clear()
        browser.find_element_by_id('u').send_keys('980639151')
        browser.find_element_by_id('p').clear()
        browser.find_element_by_id('p').send_keys('yzy19960304')
        browser.find_element_by_id('login_button').click()
    browser.implicitly_wait(3)
    try:
        browser.find_element_by_id('QM_OwnerInfo_Icon')
        b = True
    except:
        b = False
    if b == True:
        frame = browser.find_element_by_xpath('//*[@id="app_canvas_frame"]')
        print(frame)
        browser.switch_to.frame("app_canvas_frame")
        contents = browser.find_elements_by_css_selector('.content')
        times = browser.find_elements_by_css_selector('.c_tx.c_tx3.goDetail')
        for content, tim in zip(contents,times):
            data = {
                'time': tim.text,
                'content': content.text
            }
            qq_shuo.insert_one(data)
    browser.quit()

if __name__ == '__main__':
    qq_list = []
    with open('./QQmail.csv','r+') as file:
        reader = csv.reader(file)
        for row in reader:
            # print(row[2])
            qq_list.append(row[2].split('@')[0])
        for item in qq_list:
            get_info(item)
            time.sleep(3)
    #
    # content = qq_shuo.find()
    # for i in content:
    #     print(i)
